package todo_plan

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"tao-admin/internal/model"
)

type PlanCalendarService struct {
	PlanCalendarManager *PlanCalendarManager
}

func NewPlanCalendarService() *PlanCalendarService {
	return &PlanCalendarService{
		PlanCalendarManager: &PlanCalendarManager{},
	}
}

func (service *PlanCalendarService) GetPlanCalendarInfos(ctx *gin.Context) ([]model.ToDoCalendarTab, int64, error) {
	condition := &SearchPlanCalendarCondition{}
	if content, isExist := ctx.GetQuery("content"); isExist == true {
		condition.Content = &content
	}
	if startTime, isExist := ctx.GetQuery("startTime"); isExist == true {
		condition.StartTime = &startTime
	}
	if endTime, isExist := ctx.GetQuery("endTime"); isExist == true {
		condition.EndTime = &endTime
	}

	list, total, err := service.PlanCalendarManager.SearchPlanCalendarByConditionMng(ctx, condition)
	if err != nil {
		return nil, 0, err
	}
	return list, total, nil
}

func (service *PlanCalendarService) CreatePlanCalendarItem(ctx *gin.Context) (err error, msg string) {
	var item model.ToDoCalendarTab
	bodyBytes, err := ioutil.ReadAll(ctx.Request.Body)
	if err != nil {
		return err, "数据解析出错！(Read Request.Body)"
	}
	err = json.Unmarshal(bodyBytes, &item)
	if err != nil {
		return err, "数据解析出错！(Unmarshal)"
	}

	if item.Content == nil || item.StartTime == nil || item.EndTime == nil {
		return nil, "存在必填项未填写！"
	}
	err = service.PlanCalendarManager.CreatePlanCalendarMng(ctx, item)
	if err != nil {
		return err, "插入数据出错！"
	}
	return nil, ""
}

func (service *PlanCalendarService) UpdatePlanCalendarItem(ctx *gin.Context) (err error, msg string) {
	var item model.ToDoCalendarTab
	bodyBytes, err := ioutil.ReadAll(ctx.Request.Body)
	if err != nil {
		return err, "数据解析出错！(Read Request.Body)"
	}
	err = json.Unmarshal(bodyBytes, &item)
	if err != nil {
		return err, "数据解析出错！(Unmarshal)"
	}
	if item.Id == nil {
		return nil, "Id必传！"
	}
	err = service.PlanCalendarManager.UpdatePlanCalendarMng(ctx, item)
	if err != nil {
		return err, "更新数据出错！"
	}
	return nil, ""
}

func (service *PlanCalendarService) DeletePlanCalendarItem(ctx *gin.Context) (err error, msg string) {
	var item model.ToDoCalendarTab
	bodyBytes, err := ioutil.ReadAll(ctx.Request.Body)
	if err != nil {
		return err, "数据解析出错！(Read Request.Body)"
	}
	err = json.Unmarshal(bodyBytes, &item)
	if err != nil {
		return err, "数据解析出错！"
	}
	if item.Id == nil {
		return nil, "Id必传！"
	}
	err = service.PlanCalendarManager.DeletePlanCalendarMng(ctx, item)
	if err != nil {
		return err, "删除数据出错！"
	}
	return nil, ""
}
